const http = require('http');
const axios = require('axios');
const url = require('url');
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);


const proxy = http.createServer(async (req, res) => {

    res.setHeader('Content-Type', 'application/json;chartset=utf-8');

    // 进行代理请求
    let requestUrl = req.url;

    console.log(requestUrl);

    let obj = url.parse(requestUrl, true);

    console.log(obj);

    let {
        pathname
    } = obj;



    if (pathname == '/api/v1/maizuo/lst') {

        let {
            query: {
                pageNum = 1,
                pageSize = 10,
            }
        } = obj;

        // 代理列表接口
        let url = `https://m.maizuo.com/gateway?cityId=440300&pageNum=${pageNum}&pageSize=${pageSize}&type=2&k=6875894`;

        let info = await axios({
            url: url,
            method: 'get',
            headers: {
                "X-Client-Info": `{"a":"3000","ch":"1002","v":"5.2.0","e":"1649762647632811891458049"}`,
                "X-Host": `mall.film-ticket.film.list`,
            }
        });

        res.end(JSON.stringify(info.data));


    } else if (pathname == '/api/v1/maizuo/detail') {
        // 代理详情接口
        let {
            query: {
                filmId
            }
        } = obj;

        if (!filmId) {
            res.end(JSON.stringify({
                status: -1,
                msg: '请传入filmId'
            }));
            return;
        }

        let url = `https://m.maizuo.com/gateway?filmId=${filmId}&k=6209750`;

        let info = await axios({
            url: url,
            method: 'get',
            headers: {
                "X-Client-Info": `{"a":"3000","ch":"1002","v":"5.2.0","e":"1649762647632811891458049"}`,
                "X-Host": `mall.film-ticket.film.info`,
            }
        });

        res.end(JSON.stringify(info.data));


    } else if (pathname == '/') {

        res.setHeader('Content-Type', 'text/html;chartset=utf-8');

        // 代表现实主页
        let html = await readFile('./template/mz.html', 'utf-8');

        res.end(html);


    } else {
        // 代理其他接口
        res.end(JSON.stringify({
            status: -1,
            msg: 'api not found!',
            data: null,
        }));

    }


})

const port = 9001;

proxy.listen(port, (error => {
    if (error) {
        console.log(error);
    } else {
        console.log(`server is running at http://localhost:${port}`);
    }
}));